<template>
	<view class="container">
		<input class="uni-input" focus placeholder="请输入ISBN" />
		<button type="default" @click="">点击查询书籍信息</button>
		<!-- 	<view class="layout">
			<button @click="click_category">当前分类id</button>
		</view> -->
		<!-- {{isbn}} -->
		<view class="example">
			<uni-forms ref="form" :model="scanData" labelWidth="80px">
				<uni-forms-item label="图书名称" name="bookName">
					<!-- <uni-easyinput v-model="book.bookName" placeholder="请输入书名" /> -->
					<uni-easyinput v-model="scanData.bookName" placeholder="请输入书名" />
				</uni-forms-item>
				<uni-forms-item label="作者" name="author">
					<uni-easyinput @blur="searchOrAddAuthor" v-model="scanData.author" placeholder="请输入作者" />
				</uni-forms-item>

				<uni-forms-item label="分类" name="category">
					<view class="category">
						<checkbox-group @change="handleChange">

							<label v-for="(item,index) in categoryList" :key="index">
								<checkbox :value="item.value" :checked="false" />{{item.name}}
							</label>

						</checkbox-group>
					</view>


				</uni-forms-item>


				<uni-forms-item label="出版社" name="press">
					<uni-easyinput @blur="searchOrAddPublish" v-model="scanData.press" placeholder="请输入出版社" />
				</uni-forms-item>
				<uni-forms-item label="ISBN" name="ISBN">
					<uni-easyinput v-model="isbn" placeholder="请输入ISBN" />
				</uni-forms-item>

				<uni-forms-item label="介绍" name="introduction">
					<uni-easyinput v-model="scanData.bookDesc" placeholder="请输入简介" />
				</uni-forms-item>

				<!-- 语言选择器 -->
				<!-- <uni-forms-item label="语言" name="language">
					<picker @change="bindPickerChange" :value="index" :range="array" range-key="name">
						<view style="padding: 20rpx;background-color: white;">{{ array[index].name }}</view>
					</picker>
				</uni-forms-item> -->

				<uni-forms-item label="语言" name="language">
					<uni-easyinput @blur="searchOrAddLanguage" v-model="scanData.language" placeholder="请输入语言" />
				</uni-forms-item>



				<uni-forms-item label="价格" name="price">
					<uni-easyinput v-model="scanData.price" placeholder="请输入价格" />
				</uni-forms-item>

				<uni-forms-item label="数量" name="number">
					<uni-easyinput v-model="book.number" placeholder="请输入数量" />
				</uni-forms-item>

				<uni-forms-item label="位置" name="location">
					<uni-easyinput v-model="book.location" placeholder="请输入位置" />
				</uni-forms-item>

				<!-- <uni-forms-item label="性别" name="sex" required>
	        <uni-data-checkbox v-model="user.sex" :localdata="sexs" />
	      </uni-forms-item> -->
			</uni-forms>
			<button type="primary" @click="submit">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		getUserProfile
	} from "@/api/system/user"
	import {
		updateUserProfile
	} from "@/api/system/user"
	import {
		// addBook,
		getAuthorId,
		getPublishId,
		getLanguageId,
		addAuthorId,
		addPublishId,
		addLanguageId,
		getCategoryList,
		addBook,

	} from "@/api/index/index"
	import {
		getBookInfo
	} from "@/api/work/work.js"
	import {
		type
	} from "os"
	export default {
		data() {
			return {
				isbn: '',
				categoryList: [], //分类数据源
				scanData: {}, //扫描数据源
				book: {
					name: "",
					author: "",
					publish: "",
					isbn: "",
					introduction: "",
					language: "",
					price: "",
					number: "",
					location: "",
					createBy: "1",
					categoryId: "",
					url: "",
					createTime: ""
				},

				rules: {
					bookName: {
						rules: [{
							required: true,
							errorMessage: '书名不能为空'
						}]
					},

					language: {
						rules: [{
							required: true,
							errorMessage: '语言不能为空'
						}]
					},

					// location: {
					//   rules: [{
					//     required: true,
					//     errorMessage: '位置不能为空'
					//   }]
					// },

					price: {
						rules: [{
							required: true,
							errorMessage: '价格不能为空'
						}]
					},
					// introduction: {
					//   rules: [{
					//     required: true,
					//     errorMessage: '介绍不能为空'
					//   }]
					// },
					isbn: {
						rules: [{
							required: true,
							errorMessage: 'ISBN不能为空'
						}]
					},
					author: {
						rules: [{
							required: true,
							errorMessage: '作者不能为空'
						}]
					},
					press: {
						rules: [{
							required: true,
							errorMessage: '出版社不能为空'
						}, {
							format: 'publish',
							errorMessage: '请输入正确的出版社'
						}]
					}
				}
			}
		},
		onLoad(option) {
			this.getUser()
			// this.scanData = JSON.parse(decodeURIComponent(option.scanData));
			//进入页面查询数据库是否有这本书
			getBookInfo({
				"pageNum": "1",
				"pageSize": "10",
				"searchByName": option.isbn
			}).then(res => {
				console.log("数据库查询", res);
			})
			// 进入页面请求分类数据
			getCategoryList({
				type: "category"
			}).then(res => {
				this.categoryList = res.data
				console.log("分类数据源", this.categoryList);
			})
			console.log("scanData", option.scanData);
			this.isbn = option.isbn

			// console.log("scanData",this.scanData);
			// console.log("isbn",this.isbn);
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},

		methods: {
			handleChange(e) {
				if (e.detail.value.join(',') != '') {
					this.book.categoryId = e.detail.value.join(',')
				}
				console.log(e.detail.value.join(','));
				// console.log(typeof(e.detail.value));
			},
			//分类多选框
			showCategory() {

				uni.showActionSheet({
					itemList: ['A', 'B', 'C'],
					success: function(res) {
						console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},

			//处理提交时间函数
			handleTime() {
				// 创建一个 Date 对象
				var today = new Date();

				// 获取年、月、日、时、分、秒
				var year = today.getFullYear();
				var month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
				var day = today.getDate();
				var hours = today.getHours();
				var minutes = today.getMinutes();
				var seconds = today.getSeconds();

				// 格式化输出
				var formattedTime = year + "-" +
					(month < 10 ? "0" : "") + month + "-" +
					(day < 10 ? "0" : "") + day + " " +
					(hours < 10 ? "0" : "") + hours + ":" +
					(minutes < 10 ? "0" : "") + minutes + ":" +
					(seconds < 10 ? "0" : "") + seconds;
				this.book.createTime = formattedTime

				// console.log(this.addForm.createTime);
				// "2023-11-08 19:05:05"
			},

			// 查询作者id无则添加作者
			searchOrAddAuthor() {
				console.log("查询作者id中...");
				//后端 查询作者id号
				getAuthorId({
					"type": "author",
					"keyWord": this.scanData.author
				}).then(res => {
					// 查询不到id号
					console.log("作者", res);
					if (res.data.length === 0) {
						console.log("作者id未查到，执行添加");
						// 添加作者接口
						addAuthorId({
							"value": [this.scanData.author],
							"type": "author"
						}).then(res => {

							this.book.author = String(res.data)
							console.log("返回的作者id是", res.data);
						}).catch(err => {
							console.log("添加作者号错误");
						})
					} else {
						this.book.author = res.data[0].authorValue
					}
				})
			},

			// 查询出版社id无则添加出版社
			searchOrAddPublish() {
				//后端 查询出版社id号
				getPublishId({
					"type": "publish",
					"keyWord": this.scanData.press
				}).then(res => {
					console.log("出版社", res);
					// 查询不到id号
					if (res.data.length === 0) {
						console.log("出版社号查询失败");
						// 添加出版社接口
						addPublishId({
							"value": [this.scanData.press],
							"type": "publish"
						}).then(res => {

							this.book.publish = String(res.data)
							console.log("新增出版社号成功", res.data);
						}).catch(err => {
							console.log("添加出版社号错误");
						})
					} else {
						this.book.publish = res.data[0].publishValue
					}
				})
			},

			// 查询语言id无则添加语言
			searchOrAddLanguage() {
				console.log("进入语言查询方法...");
				//后端 查询语言id号
				getLanguageId({
					"type": "language",
					"keyWord": this.scanData.language
				}).then(res => {
					console.log("查询到的语言信息", res);
					// 查询不到id号
					if (res.data.length === 0) {
						//添加语言接口
						addLanguageId({
							"value": [this.scanData.language],
							"type": "language"
						}).then(res => {

							this.book.language = String(res.data)
							console.log("新增语言返回值",res);
						}).catch(err => {
							console.log("添加语言错误");
						})
					} else {
						console.log("查询到的语言值",res);
						this.book.language = res.data[0].languageValue
					}
				})
			},

			getUser() {
				getUserProfile().then(response => {
					this.user = response.data
				})
			},

			// 添加书籍
			submit(ref) {
				// this.searchOrAddAuthor(),
				// 	this.searchOrAddPublish(),
				// 	this.searchOrAddLanguage(),
					this.handleTime()
				// this.book.language = "1"
				// this.searchOrAddLanguage(),
				// this.book = this.scanData
				// console.log("提交的scandata:", this.scanData);
					this.book.name = this.scanData.bookName,
					this.book.isbn = this.isbn,
					this.book.introduction = this.scanData.bookDesc,
					this.book.price = this.scanData.price
					// this.book.url = this.scanData.pictures.split('"')[1]
					this.book.url = ""
				// this.book.number = "1",
				this.$refs.form.validate().then(res => {
					console.log("提交的信息", this.book);

					setTimeout(() => {
						addBook(this.book).then(res => {
							console.log(res);
							uni.switchTab({
								url: '/pages/work/index',

							})
						}).catch(err => {
							console.log("添加书籍失败");
						})
					}, 500)

				})

			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #ffffff;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}

	//分类框
	.category {
		border: 1px solid gray;
	}

	.uni-list-cell {
		justify-content: flex-start
	}
</style>